package com.my.basics.demo.demo01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author mars
 * @date 2025-04-11 15:50
 */
@Slf4j
public class HelloNettyServerHandler extends ChannelHandlerAdapter {

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        try {
//            while (in.isReadable()) {
            String msgStr = in.toString(CharsetUtil.UTF_8);
            log.info("receive client msg : {}", msgStr);
            if (msgStr.endsWith("reply")) {
                String replyMsg = "Hello, this is server reply!";
                ctx.channel().writeAndFlush(Unpooled.copiedBuffer(replyMsg, CharsetUtil.UTF_8));
            }
//            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
